//设置字体
window.onload = function() {
    var wWidth= document.documentElement.clientWidth>750? 750:document.documentElement.clientWidth;
    document.documentElement.style.fontSize =wWidth / 22.8571 + 'px';
}
var app = {
    url: {
        api_base:Newbase,     //测试
    },
    post: function(_url, _data, su_fn, bool) {
        console.log(bool)
        if (bool == true) {
            loader.show();
        }
        $.ajax({
            url: _url,
            data: _data,
            type: "post",
            datatype: 'json',
            success: function(msg, req) {
                if (bool == true) {
                    loader.hide();
                }
                su_fn(msg, req)
            },
            error: function(msg, textStatus) {
                if (bool == true) {
                    loader.hide();
                }
                mui.alert('系统错误！请稍后再试！', '提示');
            }
        })
    },
    posttoken: function(_url, _data, su_fn) {
        $.ajax({
            url: _url,
            data: _data,
            type: "post",
            datatype: 'json',
            beforeSend: function(xhr) {
                var token = JSON.parse(eval('(' + app.getItem('COOKIE_TOKEN_KEY') + ')')).accessToken;
                //var token='504d3991-fc87-4904-a409-6c81b76042d1'; 
                xhr.setRequestHeader("authorization", "Bearer " + app.encode(token));
            },
            success: function(msg, req) {
                su_fn(msg, req)
            },
            error: function(msg, req) {
                console.log(msg.status);
                if (msg.status == 401) {
                    app.removeItem('COOKIE_TOKEN_KEY');
                    var href = window.location.href;
                    var data = {
                        originUrl: href
                    }
                    app.ajaxWX(app.url.api_base + 'get-wechat-auth-link', data, function(res) {
                        if (res.code == 0) {
                            window.location.href = res.data.wechatAuthUrl;
                        }
                    }, function() {})
                } else {
                    mui.alert(msg.status, '提示');
                }
            }
        })
    },
    //获取企业号授权
    ajaxWX: function(_url, _p, _su_fn, _er_fn, load_config) {
        var isLoad = false;
        var loadTitle = undefined;
        if (load_config != undefined) {
            isLoad = load_config.load;
            loadTitle = load_config.title;
        }
        $.ajax({
            url: _url,
            data: _p,
            dataType: "json",
            type: "post",
            beforeSend: function() {
                if (isLoad) {
                    if (loadTitle == undefined) {
                        $.showPreloader();
                    } else {
                        $.showPreloader(loadTitle);
                    }
                }
            },
            success: function(data) {
                // $.hidePreloader();
                _su_fn(data);
            },
            error: function() {
                _er_fn;
            }
        })
    },
    //获取userToken
    getcookie: function(url) {
        // if(this.getItem('COOKIE_TOKEN_KEY') == null){
        if (this.readCookie('COOKIE_TOKEN_KEY') == null) {
            var href = window.location.href;
            var data = {
                originUrl: url
            }
            this.ajaxWX(this.url.api_base + 'get-wechat-auth-link', data, function(res) {
                if (res.code == 0) {
                    window.location.href = res.data.wechatAuthUrl;
                }
            }, function() {})
        } else {
            var token = app.readCookie('COOKIE_TOKEN_KEY');
            app.addItem('COOKIE_TOKEN_KEY', token);
            return true;

        }
        // }else{
        //     return true;
        // }

    },
    //读取数据
    readCookie: function(name) {
        var arr = document.cookie.split('; '); //多个cookie值是以; 分隔的，用split把cookie分割开并赋值给数组
        for (var i = 0; i < arr.length; i++) //历遍数组
        {
            var arr2 = arr[i].split('='); //原来割好的数组是：user=simon，再用split('=')分割成：user simon 这样可以通过arr2[0] arr2[1]来分别获取user和simon 
            if (arr2[0] == name) //如果数组的属性名等于传进来的name
            {
                return unescape(arr2[1]); //就返回属性名对应的值
            }
        }
        return null //没找到就返回空

    },
    //base64编码
    utf8Decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = 0;
        var c1 = 0;
        var c2 = 0;
        while (i < utftext.length) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    },
    //base64编码
    encode: function(input) {
        var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = this.utf8Decode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }
        return output;
    },
    go: function(_url, ignoreCache) {
        if (ignoreCache === undefined) {
            ignoreCache = false;
        }
        //$.router.load(_url,true)
        window.location.href = _url;
    },
    back: function() {
        //$.router.back();
        window.history.back();
    },
    //本地存储  name为字符串   如果是value数组存储之前要类型装换成字符串
    addItem: function(name, value) {

        localStorage.setItem(name, value);
    },
    //删除本地数据
    removeItem: function(name) {
        localStorage.removeItem(name);
    },
    //获取本地数据
    getItem: function(name) {
        var v = localStorage.getItem(name);
        return (v == undefined ? null : v);
    },
    //存储本地用户ID
    putLoginUser: function(user) {
        sessionStorage.setItem("login_user", user);
    },
    //获取本地用户ID
    getLoginUser: function() {
        return sessionStorage.getItem("login_user");
    },
    //删除本地用户ID
    removeLoginUser: function() {
        return sessionStorage.removeItem("login_user");
    },
    //判断用户是否登录
    isLogin: function() {
        var userId = sessionStorage.getItem("login_user");
        if (userId == null || userId === undefined || userId == "") {
            return false;
            app.go("login.html");
        } else {
            return true;
        }
    },
    //包含操作系统目录/mnt并以其开头,则处理掉该目录
    replaceMnt: function(imgUrl) {
        if (imgUrl == null || imgUrl === undefined || imgUrl == "" || (imgUrl.indexOf("/mnt") < 0)) {
            return imgUrl;
        } else {
            imgUrl = imgUrl.replace("/mnt", "");
            return imgUrl;
        }
    },
    getParameterByName: function(name) {
        var match = RegExp('[?&]' + name + '=([^&]*)')
            .exec(window.location.search);
        return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
    },
    //去除空格
    Trim: function(str, is_global) {
        var result;
        result = str.replace(/(^\s+)|(\s+$)/g, "");
        if (is_global.toLowerCase() == "g") {
            result = result.replace(/\s/g, "");
        }
        return result;
    },

};

Date.prototype.Format = function(fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
//封装loader
var loader = {
    show: function() {
        var Lbody = document.body;
        var mark = document.createElement("div");
        mark.setAttribute("id", "loadermark");
        var lidivbox = document.createElement("div");
        lidivbox.setAttribute("id", "loaderbox");
        var lidp = document.createElement("p");
        lidp.innerHTML = "加载中...";
        var lidiv = document.createElement("div");
        lidiv.setAttribute("class", "sk-fading-circle");
        var lidiv1 = document.createElement("div");
        lidiv1.setAttribute("class", "sk-circle sk-circle1");
        var lidiv2 = document.createElement("div");
        lidiv2.setAttribute("class", "sk-circle sk-circle2");
        var lidiv3 = document.createElement("div");
        lidiv3.setAttribute("class", "sk-circle sk-circle3");
        var lidiv4 = document.createElement("div");
        lidiv4.setAttribute("class", "sk-circle sk-circle4");
        var lidiv5 = document.createElement("div");
        lidiv5.setAttribute("class", "sk-circle sk-circle5");
        var lidiv6 = document.createElement("div");
        lidiv6.setAttribute("class", "sk-circle sk-circle6");
        var lidiv7 = document.createElement("div");
        lidiv7.setAttribute("class", "sk-circle sk-circle7");
        var lidiv8 = document.createElement("div");
        lidiv8.setAttribute("class", "sk-circle sk-circle8");
        var lidiv9 = document.createElement("div");
        lidiv9.setAttribute("class", "sk-circle sk-circle9");
        var lidiv10 = document.createElement("div");
        lidiv10.setAttribute("class", "sk-circle sk-circle10");
        var lidiv11 = document.createElement("div");
        lidiv11.setAttribute("class", "sk-circle sk-circle11");
        var lidiv12 = document.createElement("div");
        lidiv12.setAttribute("class", "sk-circle sk-circle12");
        lidivbox.appendChild(lidp);
        lidiv.appendChild(lidiv1);
        lidiv.appendChild(lidiv2);
        lidiv.appendChild(lidiv3);
        lidiv.appendChild(lidiv4);
        lidiv.appendChild(lidiv5);
        lidiv.appendChild(lidiv6);
        lidiv.appendChild(lidiv7);
        lidiv.appendChild(lidiv8);
        lidiv.appendChild(lidiv9);
        lidiv.appendChild(lidiv10);
        lidiv.appendChild(lidiv11);
        lidiv.appendChild(lidiv12);
        lidivbox.appendChild(lidiv);
        Lbody.appendChild(mark)
        Lbody.appendChild(lidivbox)
    },
    hide: function() {
        var Lbody = document.body;
        var loaderbox = document.getElementById("loaderbox");
        var loadermark = document.getElementById("loadermark");
        Lbody.removeChild(loaderbox)
        Lbody.removeChild(loadermark)
    }
};